﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DM4;
using UrielGuy.SyntaxHighlightingTextBox;
using DM4Script;

namespace DM4Client.AddEditForms
{
    public partial class FrmAddEditScript : XtraForm
    {
        public int ScriptId = DM4Consts.DefaultNULLId;
        private readonly SyntaxHighlightingTextBox _stbScript;
        private readonly SyntaxHighlightingTextBox _stbScriptLog;
        public OperationResult Result = new OperationResult();

        public const string FrmNewScriptCaption = "New script adding";

        public FrmAddEditScript(int scrId = DM4Consts.DefaultNULLId)
        {
            ScriptId = scrId;

            InitializeComponent();

            _stbScript = Common.CreateScriptEditControl(gcScriptText.Controls, Appearance.BackColor);
            _stbScriptLog = Common.CreateScriptLogControl(gcScriptLog.Controls, Appearance.BackColor);
        }

        private void FrmAddEditScriptShown(object sender, EventArgs e)
        {

            if (ScriptId == DM4Consts.DefaultNULLId)
            {
                Text = FrmNewScriptCaption;
            }
            else
            {
                DataRow[] drcoll = FrmMain.DtScripts.Select(String.Format("[{0}]={1}", "scr_id", ScriptId));
                if (drcoll.Length > 0)
                {
                    DataRow dr = drcoll[0];
                    Text = String.Format("Edit script: {0}", dr["scr_name"]);
                    tbName.Text = dr["scr_name"].ToString();
                    tbDescription.Text = dr["scr_description"].ToString();
                    _stbScript.Text = dr["scr_text"].ToString();
                }
                else
                {
                    Text = FrmNewScriptCaption;
                }
            }

            tbName.Focus();
        }

        private void btnOkClick(object sender, EventArgs e)
        {
            try
            {
                if (String.IsNullOrEmpty(tbName.Text))
                {
                    MessageBox.Show(this, "Script name is empty", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (ScriptId == DM4Consts.DefaultNULLId)
                {
                    Result = FrmMain.AddScript(tbName.Text.Trim(), tbDescription.Text.Trim(), _stbScript.Text);
                }
                else
                {
                    Result = FrmMain.EditScript(ScriptId, tbName.Text.Trim()
                        , tbDescription.Text.Trim(), _stbScript.Text);
                }

                if (Result.Result > 0)
                {
                    DialogResult = DialogResult.OK;
                    Close();
                }
                else
                {
                    MessageBox.Show(this, Result.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                string m = ScriptId == DM4Consts.DefaultNULLId
                    ? "Error of script creating"
                    : "Error of script editing";
                FrmMain.WriteError(m + Environment.NewLine + ex.Message);
                Close();
            }
        }

        private void btnCheckClick(object sender, EventArgs e)
        {
            _stbScriptLog.Text = "";

            if (!String.IsNullOrEmpty(_stbScript.Text))
            {
                var parse = new ScriptParse();
                parse.Analize(_stbScript.Text);
                foreach (var log in parse.Logs)
                {
                    _stbScriptLog.Text += log.Message() + "\n";
                    //if (log._error)
                    //{
                    //    StbScriptLog.SelectAll();
                    //    StbScriptLog.SelectionColor = Color.Red;

                    //    if (log._selectError != null)
                    //    {
                    //        StbScriptInfo.Select(log._selectError.x, 3);
                    //        StbScriptInfo.SelectionBackColor = Color.Red;
                    //    }

                    //}
                }
            }
        }

        protected override bool ProcessDialogKey(Keys keyData)
        {
            if (ckey(keyData, Keys.Control, Keys.Enter))
                btnOkClick(null, null);

            return base.ProcessDialogKey(keyData);
        }

        bool ckey(Keys keyData, params Keys[] keys)
        {
            if (keys == null) return false;

            for (int i = 0; i < keys.Length; i++)
                if ((keyData & keys[i]) != keys[i])
                    return false;

            return true;
        }
    }
}